package cn.rukbat.demo3.interceptor;

import cn.rukbat.demo3.util.PasswordlessTokenUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

// Spring Boot 2.x
// Java 8+
// Servlet API 4.0+
//import javax.servlet.http.HttpServletRequest;
//import javax.servlet.http.HttpServletResponse;

// Spring Boot 3.x
// Java 17+
// Servlet API 5.0+
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

import java.util.Arrays;
import java.util.List;

@Component
public class PasswordlessResourceInterceptor implements HandlerInterceptor {
    
    @Autowired
    private PasswordlessTokenUtil tokenUtil;
    
    // 需要Token验证的静态资源路径
    private final List<String> protectedPaths = Arrays.asList(
        "/protected/css/",
        "/protected/js/", 
        "/protected/images/",
        "/protected/downloads/",
        "/protected/assets/"
    );
    
    // 公开资源路径（无需验证）
    private final List<String> publicPaths = Arrays.asList(
        "/public/",
        "/error"
    );
    
    @Override
    public boolean preHandle(HttpServletRequest request, 
                           HttpServletResponse response, 
                           Object handler) throws Exception {
        
        String requestURI = request.getRequestURI();
        
        // 检查是否是公开资源
        if (isPublicResource(requestURI)) {
            return true;
        }
        
        // 检查是否是受保护资源
        if (isProtectedResource(requestURI)) {
            String token = request.getParameter("token");
            String timestampStr = request.getParameter("t");
            String clientId = request.getParameter("clientId");
            
            if (token == null || timestampStr == null) {
                return sendErrorResponse(response, "Missing token or timestamp");
            }
            
            try {
                Long timestamp = Long.parseLong(timestampStr);
                boolean isValid;
                
                if (clientId != null) {
                    // 使用预共享密钥验证
                    isValid = tokenUtil.validateTokenWithPSK(token, requestURI, timestamp, clientId);
                } else {
                    // 标准验证
                    isValid = tokenUtil.validateToken(token, requestURI, timestamp);
                }
                
                if (!isValid) {
                    return sendErrorResponse(response, "Invalid token or timestamp");
                }
                
            } catch (NumberFormatException e) {
                return sendErrorResponse(response, "Invalid timestamp format");
            }
        }
        
        return true;
    }
   
    private boolean isProtectedResource(String requestURI) {
        return protectedPaths.stream().anyMatch(requestURI::startsWith);
    }
    
    private boolean isPublicResource(String requestURI) {
        return publicPaths.stream().anyMatch(requestURI::startsWith);
    }
    
    private boolean sendErrorResponse(HttpServletResponse response, String message) throws Exception {
        response.setStatus(HttpServletResponse.SC_FORBIDDEN);
        response.setContentType("application/json");
        response.getWriter().write("{\"error\": \"" + message + "\"}");
        return false;
    }
}
